<?php
  $serverName = "localhost";
  $schemaName = "askyoudb";
  $userName   = "root";
  $userPass   = "jkl888";
  
  mysql_pconnect($serverName, $userName, $userPass);
  mysql_select_db($schemaName);
  
  $tables_source = mysql_query("SHOW TABLES");
  
  while ($table = mysql_fetch_row($tables_source)) {
    $name = explode("_",$table[0]);
    $className ="";
    $fileName = "";
    foreach($name as $k) {
      $className .= ucfirst($k);
      $fileName  .= strlen($fileName)>0?ucfirst($k):$k;  
    }
    $fileName .= ".php";
    $className = "Application_Models_Rows_" . $className;
    $class = "\nclass " . $className . "{\n";
    $class .= "  public function __Construct(\$params) {
      \$this.__set(\$params);
    }\n";
    $class .= "  public function __set(\$name, \$value) {
        \$method = 'set' . ucfirst(\$name);
        if (('mapper' == \$name) || !method_exists(\$this, \$method)) {
            throw new Exception('Invalid ".$className." property');
        }
        \$this->\$method(\$value);
      }\n";
    $class .= "public function  __get(\$name) {
        \$method = 'set' . ucfirst(\$name);
        if (('mapper' == \$name) || !method_exists(\$this, \$method)) {
            throw new Exception('Invalid User property');
        }
        return \$this->\$method();
      }\n";
    $params_source = mysql_query("DESCRIBE " . $table[0]); 
    
    $parametrs = "";
    $getters   = "";
    $setters   = "";
    while ($param = mysql_fetch_assoc($params_source)) {
      $parametrs .= "  private \$" . $param['Field'] . ";\n";
      $setters   .= "  public function set" . ucfirst($param['Field']) . "(\$value) {\n  \$this->" . $param['Field'] . " = \$value;\n  }\n";
      $getters   .= "  public function get" . ucfirst($param['Field']) . "() {\n  return \$this->" . $param['Field'] . ";\n  }\n";
    } 
    $class .= $parametrs;
    $class .= $setters;
    $class .= $getters;
    $class .= "}";
    
    $dir = "./tables/";
    if (file_exists($dir.$fileName.".php")) unlink($dir.$fileName.".php");

    $fileHandle = fopen($dir.$fileName, 'w') or die("can't open file");
    fwrite($fileHandle, '<?php'.$class);
    fclose($fileHandle);

    echo "<h2>".$fileName."</h2><pre style=\"border: 1px solid black;\">" . $class . "</pre>";
  }
?>
